class Sold < ActiveRecord::Base
  attr_accessible :bill_id, :quantity, :sale_cost, :stock_id,:tax_percentage, :commission_percentage, :has_returns
  belongs_to :bill
  belongs_to :stock

  validates :quantity, :numericality => { :only_integer => true, :greater_than => 0 }
  validate :check_if_stock_has_enough_quantity
  validates :sale_cost, :numericality => { :greater_than => 0 }
  validates :tax_percentage, :numericality => { :greater_than_or_equal_to => 0 }
  validates :commission_percentage, :numericality => { :greater_than_or_equal_to => 0 }

  after_save :update_stock_on_create, :on => ['create'] 

  def update_stock_on_create
    stock.available_quantity = stock.available_quantity - quantity
    stock.save
  end

  def check_if_stock_has_enough_quantity
    errors[:quantity] = "exceeding stock availablity" if stock.available_quantity < quantity
  end
end
